"""
添加账号对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                           QLineEdit, QPushButton, QSpinBox, QDoubleSpinBox,
                           QRadioButton, QButtonGroup, QMessageBox, QFrame)
from PyQt6.QtCore import Qt, pyqtSignal
from datetime import datetime
import logging

from com.db.order_account_manager import OrderAccountManager
from com.device_generator import generate_device_id
from .login_dialog import LoginDialog

logger = logging.getLogger(__name__)

class AddAccountDialog(QDialog):
    """添加账号对话框"""
    
    # 添加账号成功的信号
    account_added = pyqtSignal()
    
    def __init__(self, parent=None, account_id=None):
        super().__init__(parent)
        logger.debug("初始化添加账号对话框")
        self.account_manager = OrderAccountManager()
        self.account_id = account_id  # 保存账号ID，用于区分是添加还是编辑
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        logger.debug("开始初始化UI")
        self.setWindowTitle("新增账号")
        self.setFixedSize(600, 500)
        self.setStyleSheet("""
            QDialog {
                background-color: white;
            }
            QLabel {
                font-size: 12px;
                color: #606266;
            }
            QLineEdit, QSpinBox, QDoubleSpinBox {
                padding: 8px;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                color: #606266;
            }
            QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus {
                border-color: #409eff;
            }
            QPushButton {
                padding: 8px 20px;
                border-radius: 2px;
                font-size: 12px;
            }
            QPushButton#confirmBtn {
                background-color: #409eff;
                color: white;
                border: none;
            }
            QPushButton#confirmBtn:hover {
                background-color: #66b1ff;
            }
            QPushButton#cancelBtn {
                background-color: white;
                color: #606266;
                border: 1px solid #dcdfe6;
            }
            QPushButton#cancelBtn:hover {
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
            }
            QRadioButton {
                font-size: 12px;
                color: #606266;
            }
            QRadioButton::indicator {
                width: 16px;
                height: 16px;
            }
        """)
        
        layout = QVBoxLayout(self)
        layout.setSpacing(20)
        layout.setContentsMargins(30, 20, 30, 20)
        
        # uu token
        token_layout = QHBoxLayout()
        token_label = QLabel("uu token")
        token_label.setFixedWidth(100)
        self.token_input = QLineEdit()
        self.token_input.setPlaceholderText("请输入token")
        login_btn = QPushButton("登录验证")
        logger.debug("创建登录验证按钮")
        login_btn.setStyleSheet("""
            QPushButton {
                background-color: #409EFF;
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        login_btn.setObjectName("verifyBtn")
        login_btn.clicked.connect(self.show_login_dialog)
        logger.debug("已连接登录验证按钮的点击事件")
        token_layout.addWidget(token_label)
        token_layout.addWidget(self.token_input)
        token_layout.addWidget(login_btn)
        
        # token提示
        token_tip = QLabel("我们强烈建议您token全部加密后再使用，所以此处仅支持登录验证获取token")
        token_tip.setStyleSheet("color: #f56c6c; font-size: 12px;")
        
        # 账号名称
        name_layout = QHBoxLayout()
        name_label = QLabel("账号名称")
        name_label.setFixedWidth(80)
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("默认为 uu账号别称，也可随意填写你觉得好记的名称")
        name_layout.addWidget(name_label)
        name_layout.addWidget(self.name_input)
        
        # 账号名称提示
        name_tip = QLabel("账号名不能为空")
        name_tip.setStyleSheet("color: #f56c6c; font-size: 12px;")
        
        # 余额限制
        balance_layout = QHBoxLayout()
        balance_label = QLabel("余额限制")
        balance_label.setFixedWidth(80)
        self.balance_limit_spin = QDoubleSpinBox()
        self.balance_limit_spin.setRange(0, 999999)
        self.balance_limit_spin.setValue(0.1)
        self.balance_limit_spin.setDecimals(1)
        self.balance_limit_spin.setSingleStep(0.1)
        balance_tip = QLabel("(低于此金额将停止扫货)")
        balance_tip.setStyleSheet("color: #909399; font-size: 12px;")
        balance_layout.addWidget(balance_label)
        balance_layout.addWidget(self.balance_limit_spin)
        balance_layout.addWidget(balance_tip)
        balance_layout.addStretch()
        
        # 余额监控
        balance_monitor_layout = QHBoxLayout()
        balance_monitor_label = QLabel("余额监控")
        balance_monitor_label.setFixedWidth(100)
        self.monitor_yes = QRadioButton("开启")
        self.monitor_no = QRadioButton("关闭")
        self.monitor_yes.setChecked(True)  # 默认开启
        balance_monitor_group = QButtonGroup(self)
        balance_monitor_group.addButton(self.monitor_yes)
        balance_monitor_group.addButton(self.monitor_no)
        balance_monitor_layout.addWidget(balance_monitor_label)
        balance_monitor_layout.addWidget(self.monitor_yes)
        balance_monitor_layout.addWidget(self.monitor_no)
        balance_monitor_layout.addStretch()
        
        # 余额监测提示
        monitor_tip = QLabel("开启余额监测后，每下单时可用余额小于该数值将会全部账号停止下单。\n适用于余额不足与买太大量订单数量从而避免账号安全。")
        monitor_tip.setStyleSheet("color: #909399; font-size: 12px;")
        monitor_tip.setWordWrap(True)
        
        # 失败监测
        fail_layout = QHBoxLayout()
        fail_label = QLabel("失败监测")
        fail_label.setFixedWidth(80)
        self.fail_monitor_spin = QSpinBox()
        self.fail_monitor_spin.setRange(0, 999)
        self.fail_monitor_spin.setValue(0)
        fail_layout.addWidget(fail_label)
        fail_layout.addWidget(self.fail_monitor_spin)
        fail_layout.addStretch()
        
        # 失败监测提示
        fail_tip = QLabel("当该值为0时，表示关闭失败监测；\n当该值大于0时，表示开启失败监测，当同一单订单失败次数大于等于该值时将不再继续下单，直到重启软件后恢复。")
        fail_tip.setStyleSheet("color: #909399; font-size: 12px;")
        fail_tip.setWordWrap(True)
        
        # 购买方式
        buy_layout = QHBoxLayout()
        buy_label = QLabel("购买方式")
        buy_label.setFixedWidth(80)
        self.auto_buy = QRadioButton("批量购买")
        self.single_buy = QRadioButton("加密购买")
        self.auto_buy.setChecked(True)
        buy_group = QButtonGroup(self)
        buy_group.addButton(self.auto_buy)
        buy_group.addButton(self.single_buy)
        buy_layout.addWidget(buy_label)
        buy_layout.addWidget(self.auto_buy)
        buy_layout.addWidget(self.single_buy)
        buy_layout.addStretch()
        
        # 购买方式提示
        buy_tip = QLabel("(仅在单任务出货，需要批量购买时更快)")
        buy_tip.setStyleSheet("color: #909399; font-size: 12px;")
        
        # 是否启用
        enable_layout = QHBoxLayout()
        enable_label = QLabel("是否启用")
        enable_label.setFixedWidth(80)
        self.enable_yes = QRadioButton("是")
        self.enable_no = QRadioButton("否")
        self.enable_yes.setChecked(True)
        enable_group = QButtonGroup(self)
        enable_group.addButton(self.enable_yes)
        enable_group.addButton(self.enable_no)
        enable_layout.addWidget(enable_label)
        enable_layout.addWidget(self.enable_yes)
        enable_layout.addWidget(self.enable_no)
        enable_layout.addStretch()
        
        # 按钮
        btn_layout = QHBoxLayout()
        confirm_btn = QPushButton("确定")
        confirm_btn.setObjectName("confirmBtn")
        confirm_btn.clicked.connect(self.accept)  # 连接到accept槽函数
        cancel_btn = QPushButton("取消")
        cancel_btn.setObjectName("cancelBtn")
        cancel_btn.clicked.connect(self.reject)
        btn_layout.addStretch()
        btn_layout.addWidget(confirm_btn)
        btn_layout.addWidget(cancel_btn)
        
        # 添加所有组件到主布局
        layout.addLayout(token_layout)
        layout.addWidget(token_tip)
        layout.addLayout(name_layout)
        layout.addWidget(name_tip)
        layout.addLayout(balance_layout)
        layout.addLayout(balance_monitor_layout)
        layout.addWidget(monitor_tip)
        layout.addLayout(fail_layout)
        layout.addWidget(fail_tip)
        layout.addLayout(buy_layout)
        layout.addWidget(buy_tip)
        layout.addLayout(enable_layout)
        layout.addStretch()
        layout.addLayout(btn_layout)

    def connect_events(self):
        """连接事件"""
        pass  

    def show_login_dialog(self):
        """显示登录对话框"""
        try:
            logger.debug("点击了登录验证按钮，准备显示登录对话框")
            dialog = LoginDialog(self)
            dialog.show()  # 先显示窗口
            logger.debug("登录对话框显示完成")
            result = dialog.exec()
            logger.debug(f"登录对话框返回结果: {result}")
            
            if result == QDialog.DialogCode.Accepted:
                logger.debug("登录成功")
                # 获取登录数据
                account_data = getattr(dialog, 'account_data', None)
                if account_data:
                    logger.debug(f"登录数据: {account_data}")
                    # 更新UI显示
                    self.token_input.setText(account_data.get('token', ''))
                    self.name_input.setText(account_data.get('nickname', ''))
                    
                    # 保存登录数据以便后续保存
                    # 确保字段名称与accept方法中期望的一致
                    self.login_data = {
                        'token': account_data.get('token', ''),
                        'uu_user_id': account_data.get('user_id', 0),
                        'user_id': account_data.get('user_id', 0),
                        'nickname': account_data.get('nickname', ''),
                        'device_id': account_data.get('device_id', ''),
                        'uk': account_data.get('uk', ''),
                        'avatar': None,
                        'steam_id': None,
                        'device_info': {}
                    }
                    QMessageBox.information(self, "提示", "登录验证成功")
                else:
                    logger.error("未获取到登录数据")
                    QMessageBox.warning(self, "错误", "未获取到登录数据")
            else:
                logger.debug("登录取消或失败")
        except Exception as e:
            logger.error(f"显示登录对话框时发生错误: {str(e)}")
            QMessageBox.warning(self, "错误", f"显示登录对话框时发生错误: {str(e)}")

    def get_form_data(self):
        """获取表单数据
        
        Returns:
            dict: 表单数据字典，包含以下字段:
                - uu_token: str, UU加速器token
                - buy_method: int, 下单类型(1:自动下单, 2:手动下单)
                - balance_limit: float, 余额限制
                - balance_monitor: int, 余额监控(1:开启, 0:关闭)
                - buy_fail_monitor: int, 购买失败监控次数
                - status: int, 状态(1:启用, 0:禁用)
        """
        try:
            # 获取表单数据
            uu_token = self.token_input.text().strip()
            buy_method = 1 if self.auto_buy.isChecked() else 2
            balance_limit = self.balance_limit_spin.value()
            balance_monitor = 1 if self.monitor_yes.isChecked() else 0
            buy_fail_monitor = self.fail_monitor_spin.value()
            status = 1 if self.enable_yes.isChecked() else 0
            
            # 验证必填字段
            if not uu_token:
                QMessageBox.warning(self, "提示", "请输入UU token")
                return None
            
            # 返回数据字典
            return {
                'uu_token': uu_token,
                'buy_method': buy_method,
                'balance_limit': balance_limit,
                'balance_monitor': balance_monitor,
                'buy_fail_monitor': buy_fail_monitor,
                'status': status,
                'create_at': str(int(datetime.now().timestamp() * 1000)),
                'update_at': int(datetime.now().timestamp() * 1000)
            }
        except Exception as e:
            logger.error(f"获取表单数据失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"获取表单数据失败: {str(e)}")
            return None

    def accept(self):
        """确认添加或编辑账号"""
        try:
            if not self.login_data:
                logger.error("登录数据为空")
                QMessageBox.warning(self, "提示", "请先登录验证")
                return
                
            # 验证uu_user_id
            uu_user_id = self.login_data.get('uu_user_id')  # 使用LoginManager处理后的字段名
            if not uu_user_id:
                logger.error("登录数据中缺少uu_user_id")
                QMessageBox.warning(self, "提示", "登录数据不完整，缺少用户ID")
                return
                
            # 检查uu_user_id是否已存在（仅在添加模式下检查）
            existing_account = None
            if not self.account_id:
                existing_account = self.account_manager.get_account_by_uu_user_id(uu_user_id)
                
            # 获取表单数据
            account_data = self.get_form_data()
            if not account_data:
                logger.error("表单数据获取失败")
                return
            
            logger.info(f"获取到的表单数据: {account_data}")
                
            # 使用登录时获取的设备ID，而不是重新生成
            device_id = self.login_data.get('device_id', '')
            logger.info(f"登录数据中的设备ID: {device_id}")
            
            # 如果设备ID为空，尝试从token中提取
            if not device_id and self.login_data.get('token'):
                try:
                    # JWT token通常由三部分组成，用.分隔，第二部分是payload
                    token_parts = self.login_data['token'].split('.')
                    if len(token_parts) >= 2:
                        import base64
                        import json
                        # 解码payload部分，处理填充问题
                        payload_part = token_parts[1]
                        # 添加填充使其长度为4的倍数
                        padding_needed = len(payload_part) % 4
                        if padding_needed:
                            payload_part += '=' * (4 - padding_needed)
                        # 使用更安全的解码方式
                        decoded = base64.urlsafe_b64decode(payload_part)
                        payload = json.loads(decoded.decode('utf-8', errors='ignore'))
                        if 'deviceId' in payload:
                            device_id = payload['deviceId']
                            logger.info(f"从token中提取设备ID: {device_id}")
                except Exception as e:
                    logger.error(f"从token提取设备ID失败: {e}")
            
            # 如果仍然为空，才生成新的
            if not device_id:
                device_id = generate_device_id()
                logger.info(f"生成了新的设备ID: {device_id}")
            
            logger.info(f"最终使用的设备ID: {device_id}")
            
            # 记录uu_user_id的值
            uu_user_id_value = self.login_data.get('uu_user_id')
            logger.info(f"登录数据中的uu_user_id: {uu_user_id_value}")
            
            # 如果uu_user_id为空，尝试从user_id获取
            if not uu_user_id_value and self.login_data.get('user_id'):
                uu_user_id_value = self.login_data.get('user_id')
                logger.info(f"从user_id获取uu_user_id: {uu_user_id_value}")
            
            # 如果仍然为空，尝试从token中提取
            if not uu_user_id_value and self.login_data.get('token'):
                try:
                    # JWT token通常由三部分组成，用.分隔，第二部分是payload
                    token_parts = self.login_data['token'].split('.')
                    if len(token_parts) >= 2:
                        import base64
                        import json
                        # 解码payload部分，处理填充问题
                        payload_part = token_parts[1]
                        # 添加填充使其长度为4的倍数
                        padding_needed = len(payload_part) % 4
                        if padding_needed:
                            payload_part += '=' * (4 - padding_needed)
                        # 使用更安全的解码方式
                        decoded = base64.urlsafe_b64decode(payload_part)
                        payload = json.loads(decoded.decode('utf-8', errors='ignore'))
                        if 'Id' in payload:
                            uu_user_id_value = int(payload['Id'])
                            logger.info(f"从token中提取uu_user_id: {uu_user_id_value}")
                except Exception as e:
                    logger.error(f"从token提取uu_user_id失败: {e}")
                
            # 获取登录数据，只添加模型中存在的字段
            account_data.update({
                'device_id': device_id,
                'uu_user_id': uu_user_id_value,  # 使用提取的uu_user_id值
                'avatar': self.login_data.get('avatar'),  # 使用LoginManager处理后的字段名
                'nickname': self.login_data.get('nickname'),  # 使用LoginManager处理后的字段名
                'steam_id': self.login_data.get('steam_id'),  # 使用LoginManager处理后的字段名
                'device_info': self.login_data.get('device_info', {}),  # 添加device_info字段
                'uk': self.login_data.get('uk'),  # 添加uk字段
                'uu_alive': 1,  # 新登录的账号默认在线
                'uu_alive_times': 0,  # 初始化存活次数
                'steam_alive': 0,  # Steam默认离线
                'safe_verify': 0,  # 默认未验证
                'pay_type': 1,  # 默认支付类型
                'update_at': int(datetime.now().timestamp() * 1000)
            })
            
            logger.info(f"更新后的账号数据: {account_data}")
            
            # 如果name为空，使用nickname作为name
            if not account_data.get('name'):
                account_data['name'] = account_data.get('nickname', '')
                logger.info(f"使用nickname作为name: {account_data['name']}")
            
            success = False
            # 判断是添加还是编辑
            if self.account_id:
                # 编辑模式
                try:
                    logger.info(f"开始更新账号，ID: {self.account_id}")
                    success = self.account_manager.update_account(self.account_id, account_data)
                    if success:
                        logger.info("账号更新成功")
                        QMessageBox.information(self, "提示", "编辑成功")
                    else:
                        logger.error("账号更新失败，account_manager.update_account返回False")
                except Exception as e:
                    logger.error(f"更新账号时发生异常: {str(e)}", exc_info=True)
                    success = False
            else:
                # 添加模式
                try:
                    logger.info("开始添加新账号")
                    # 使用之前已经检查过的existing_account变量
                    uu_user_id = account_data.get('uu_user_id')
                    
                    success = self.account_manager.add_account(account_data)
                    if success:
                        if existing_account:
                            logger.info(f"账号已存在，已更新账号 (uu_user_id: {uu_user_id})")
                            QMessageBox.information(self, "提示", "账号已存在，已更新成功")
                        else:
                            logger.info("账号添加成功")
                            QMessageBox.information(self, "提示", "添加成功")
                    else:
                        logger.error("账号添加失败，account_manager.add_account返回False")
                except Exception as e:
                    logger.error(f"添加账号时发生异常: {str(e)}", exc_info=True)
                    success = False
                    
            if success:
                self.account_added.emit()  # 发送账号添加成功的信号
                super().accept()  # 关闭对话框
            else:
                QMessageBox.critical(self, "错误", "操作失败，请检查账号信息是否完整")
                
        except Exception as e:
            logger.error(f"保存账号时发生异常: {str(e)}", exc_info=True)
            QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")
